<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Auth;
use app\common\model\Admin;
use app\common\model\Banner;
use app\common\model\Company;
use app\common\model\factory\Category;
use app\common\model\forest\Member;
use app\common\model\Goods;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\shop\Data;
use app\common\model\User;
use app\common\model\wash\Order;
use app\common\model\wash\Serviceorder;
use fast\Random;
use think\Db;
use think\Exception;
use think\Hook;
use think\Lang;

/**
 * 门店端接口
 */
class Shop extends Api
{
    protected $noNeedLogin = ['shop_info', 'sendmsg'];
    protected $noNeedRight = ['*'];




    /**
     * 门店详情
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function shop_info()
    {
        $param = $this->request->param();
        extract($param);
        $data = User::get($id, ['shopdata']);
        $this->success('', $data);
    }

    /**
     * 新增骑手
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="nickname", type="str", required=true, sample="", description="姓名")
     * @ApiParams (name="mobile", type="str", required=true, sample="", description="联系电话")
     * @ApiParams (name="username", type="str", required=true, sample="", description="登录账号")
     * @ApiParams (name="password", type="str", required=true, sample="", description="登录密码")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function add_edit_rider()
    {
        $post = $this->request->post();
        extract($post);
        if (isset($nickname) && !$nickname) {
            $this->error('姓名不能为空');
        }
        if (isset($mobile) && !$mobile) {
            $this->error('联系电话不能为空');
        }
        if (isset($username) && !$username) {
            $this->error('登录账号不能为空');
        }
        if (isset($password) && !$password) {
            $this->error('登录密码不能为空');
        }
        if ($mobile && User::getByMobile($mobile)) {
            $this->error('手机号码已存在');
        }
        $post['role'] = 'rider';
        $post['shop_id'] = $this->auth->id;
        if (isset($password) && $password) {
            $post['salt'] = Random::alnum();
            $post['password'] = md5(md5($password) .  $post['salt']);
        } else {
            unset($post['password']);
        }
        $model = new User($post);
        if (isset($id) && $id) {
            $model = $model->get($id);
            $model->isUpdate(true)->allowField(true)->save($post);
        } else {
            $post['status'] = 'normal';
            $model->isUpdate(false)->allowField(true)->save($post);
        }
        $this->success('添加成功');
    }
    /**
     * 骑手列表
     *
     */
    public function rider_list()
    {
        $shop_id = $this->auth->id;
        $list = User::where('shop_id', $shop_id)->where('role', 'rider')->paginate();
        $this->success('', $list);
    }

    /**
     * 骑手详情
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function rider_info()
    {
        $param = $this->request->param();
        extract($param);
        $data = User::get($id);
        $this->success('', $data);
    }

    /**
     * 骑手删除
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function rider_del()
    {
        $param = $this->request->param();
        extract($param);
        $user =  User::get($id);
        $res = $user->delete();
        if ($res) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**
     * 订单列表
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="keywords", type="str", required=false, sample="", description="搜索")
     * @ApiParams (name="type", type="str", required=true, description="门店状态:0=待入库,1=工厂待收,2=清洁中,3=已到店,4=已完成")
     * @ApiParams (name="page", type="int", required=false, description="页码")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function order_list()
    {
        Lang::load(APP_PATH .  'admin/lang/zh-cn/wash/order.php');
        $param = request()->param();
        extract($param);
        $user = $this->auth->getUser();
        $shop_id = $this->checkShopAuth($user);
        $order = new Order();
        if (isset($order_id) && $order_id) {
            $order->where('order.id', $order_id);
        }
        if (isset($keywords) && $keywords) {
            $order->whereLike('shop.mobile|user.mobile|factory.mobile|sn|phone', '%' . $keywords . '%');
        }
        $list = $order->with(['shop' => function ($q) {
            $q->withField('id,nickname,avatar,mobile');
        }, 'user' => function ($q) {
            $q->withField('id,nickname,avatar,mobile');
        }, 'goods' => function ($q) {
            // $q->with('cate');
        }, 'factory' => function ($q) {
            $q->withField('id,nickname,avatar,mobile');
        },])->where('order.shop_id', $shop_id)->where('shop_status', (string) $type)->whereNotIn('order.status', ['0', '-1'])->order('id desc')->paginate();
        $this->success('', $list);
    }


    /**
     * @ApiInternal
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     * @param {*} $user
     */
    private function checkShopAuth($user)
    {
        if ($user->role == 'shop') {
            $shop_id = $user->id;
        }
        if ($user->role == 'rider') {
            if (!$user->shop_id) {
                $this->responseMsg(1006, '', '没有门店');
            }
            $shop_id = $user->shop_id;
        }
        if (!isset($shop_id)) {
            $this->responseMsg(1006, '', '没有门店权限');
        }
        return $shop_id;
    }
    /**
     * 订单详情
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function order_info()
    {
        $param = request()->param();
        extract($param);
        $data = Order::get($id, ['shop', 'user', 'goods', 'factory' => function ($q) {
            $q->withField('id,nickname,avatar');
        },]);
        $this->success('', $data);
    }

    /**
     * 拍照上传
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="shop_f_image", type="str", required=true, sample="", description="正面照")
     * @ApiParams (name="shop_b_image", type="str", required=true, sample="", description="背面照")
     * @ApiParams (name="shop_images", type="str", required=false, sample="", description="多图逗号分隔")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function take_pictures()
    {
        $param = request()->param();
        extract($param);
        if (!isset($shop_f_image) || !$shop_f_image) {
            $this->error('请上传正面照');
        }
        if (!isset($shop_b_image) || !$shop_b_image) {
            $this->error('请上传背面照');
        }
        $order = Order::get($id);
        $res = $order->allowField(true)->save($param);
        if ($res) {
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    /**
     * 扫码进场
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function sweep_approach()
    {
        $param = request()->param();
        extract($param);
        $order = Order::get($id);
        if ($order->status != '1') {
            $this->error('订单状态错误');
        }
        $res = $order->allowField(true)->save(['shop_status' => '1']);
        if ($res) {


            $this->success('成功');
        }
        $this->error('失败');
    }


    /**
     * 确认回店
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function setin()
    {
        $param = request()->param();
        extract($param);
        $order = Order::get($id);
        if ($order->shop_status != '2') {
            $this->error('订单状态错误');
        }
        $res = $order->allowField(true)->save(['shop_status' => '3']);
        //发送订阅消息
        try {
            $s = sendSubTemplateMsg(
                $order->user,
                "zW7kFkUmLSIX5jIIds02_cIIKwAEWL2okr7V0acSX3I",
                [
                    'character_string7' => ['value' => $order->sn],
                    'thing6' => ['value' => $order->goods_name],
                    'thing2' => ['value' => $order->shop->nickname ?? ''],
                    'thing3' => ['value' => $order->shop->address ?? ''],
                    'time10' => ['value' => date('Y-m-d H:i')],
                ]
            );

            $params = [
                'mobile'   => $order->user->mobile ?? '',
                // 'msg'      => 1234,
                'msg'      => $order->user->nickname ?? '用户',
                'template' => 'notice_user',
            ];
            $result = Hook::listen('sms_notice', $params, null, true);
        } catch (Exception $e) {
            $this->error('消息发送失败', $e->getMessage());
        }

        if ($res) {
            $this->success('成功', $s);
        }
        $this->error('失败', $s);
    }

    /**
     * 发消息
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    function sendmsg()
    {
        $param = request()->param();
        extract($param);
        $order = Order::get($id);
        if (!$order) {
            $this->error('1005');
        }
        try {
            $s = sendSubTemplateMsg(
                $order->user,
                "zW7kFkUmLSIX5jIIds02_cIIKwAEWL2okr7V0acSX3I",
                [
                    'character_string7' => ['value' => $order->sn],
                    'thing6' => ['value' => $order->goods_name],
                    'thing2' => ['value' => $order->shop->nickname ?? ''],
                    'thing3' => ['value' => $order->shop->address ?? ''],
                    'time10' => ['value' => date('Y-m-d H:i')],
                ]
            );
        } catch (Exception $e) {
            $this->error('消息发送失败', $e->getMessage());
        }
        $this->success('成功', $s);
    }
    /**
     * 确认交付
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function setcomplate()
    {
        $param = request()->param();
        extract($param);
        $order = Order::get($id);
        if ($order->shop_status != '3') {
            $this->error('订单状态错误');
        }
        $res = $order->allowField(true)->save(['shop_status' => '4', 'status' => '4']);
        if ($res) {
            User::commission($order->money_fee + $order->pay_fee, 0, $order->sn, $order->user_id);
            $this->success('成功');
        }
        $this->error('失败');
    }


    /**
     * 门店数据
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="starttime", type="str", required=false, sample="2022-01-01", description="开始时间")
     * @ApiParams (name="endtime", type="str", required=false, sample="2022-01-01", description="结束时间")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function shop_data()
    {
        $param = request()->param();
        extract($param);
        $order = new Order;
        $money_log = new MoneyLog();
        $user = $this->auth->getUser();
        $shop_id =  $this->checkShopAuth($user);
        $order->whereNotIn('status', ['0', '-1']);
        $order->where('shop_id', $shop_id);
        $shop_ids = User::where('id', $shop_id)->value('id');

        $type = $type ?? 0;
        if ($type == 1) {
            $money_log->whereTime('createtime', 'month');
            $order->whereTime('paytime', 'month');
        } elseif ($type == 2) {
            $order->whereTime('paytime', 'week');
            $money_log->whereTime('createtime', 'week');
        } else {
            if (isset($starttime) && $starttime) {
                $order->where('paytime', '>', strtotime($starttime));
                $money_log->where('createtime', '>', strtotime($starttime));
            }
            if (isset($endtime) && $endtime) {
                $order->where('paytime', '<', strtotime($endtime));
                $money_log->where('createtime', '<', strtotime($endtime));
            }
        }
        $order->field('count(*) as num,factory_images,SUM(pay_fee+money_fee+credit_fee) as total_fee,FROM_UNIXTIME(paytime,"%Y年%m月%d日") as pay_time,FROM_UNIXTIME(paytime,"%m-%d") as time');
        $list = $order->group('pay_time')->order('paytime asc')->select();
        $money_log->field('SUM(money) as total_fee,FROM_UNIXTIME(createtime,"%Y年%m月%d日") as create_time,FROM_UNIXTIME(createtime,"%m-%d") as time');
        $money_log->whereIn('user_id', $shop_ids)->where('source_type', 200);
        $log = $money_log->group('create_time')->order('createtime asc')->select();
        $data['turnover'] = Order::where('shop_id', $shop_id)->whereTime('paytime', 'today')->whereNotIn('status', ['0', '-1'])->sum('pay_fee+money_fee');
        $data['order_num'] = Order::where('shop_id', $shop_id)->whereTime('paytime', 'today')->whereNotIn('status', ['0', '-1'])->count();
        $data['commission'] = MoneyLog::where('user_id', $shop_id)->where('type', '2')->whereTime('createtime', 'today')->sum('money');
        $this->success('', compact('list', 'log', 'data'));
    }

    /**
     * 设置营业
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="on_sale", type="integer", required=false, sample="1", description="是否营业1=是,0=否")
     * @ApiParams (name="business_hours", type="str", required=false, sample="", description="营业时间")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function setsaleinfo()
    {
        $user = $this->auth->getUser();
        $shop_id =  $this->checkShopAuth($user);
        if ($shop_id != $user->id) {
            $this->error('没有权限');
        }

        $res = $user->allowField(['on_sale', 'business_hours'])->save($this->request->post());
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }


    /**
     * 家政订单列表
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="order_id", type="integer", required=false, sample="", description="ID")
     * @ApiParams (name="keywords", type="str", required=false, sample="", description="搜索")
     * @ApiParams (name="status", type="str", required=false, sample="", description="状态:1=待上门,2=清洗中,4=已完成")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function serviceorder_list()
    {
        $param = request()->param();
        extract($param);
        $user = $this->auth->getUser();
        $shop_id =  $this->checkShopAuth($user);
        $order = new Serviceorder();
        if (isset($order_id) && $order_id) {
            $order->where('fa_wash_serviceorder.id', $order_id);
        }
        if (isset($keywords) && $keywords) {
            $order->whereLike('sn|phone', '%' . $keywords . '%');
        }
        $list = $order->with(['shop' => function ($q) {
            $q->withField('id,nickname,avatar');
        }, 'user' => function ($q) {
            $q->withField('id,nickname,avatar');
        }, 'goods' => function ($q) {
            // $q->with('cate');
        }, 'factory' => function ($q) {
            $q->withField('id,nickname,avatar');
        },])->where('fa_wash_serviceorder.shop_id', $shop_id)->where('fa_wash_serviceorder.status', (string) $status)->whereNotIn('fa_wash_serviceorder.status', ['0', '-1'])->paginate();
        $this->responseMsg(0, $list);
    }
}
